package addtwonum

type ListNode struct {
	Val  int
	Next *ListNode
}

func AddTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
	var left int
	var p, p1 *ListNode
	var getVal = func(l *ListNode) int {
		if l != nil {
			return l.Val
		}
		return 0
	}
	for l1 != nil || l2 != nil || left > 0 {
		sum := getVal(l1) + getVal(l2) + left
		left = sum / 10
		node := &ListNode{
			Val:  sum % 10,
			Next: nil,
		}
		if p == nil {
			p = node
			p1 = p
		} else {
			p1.Next = node
			p1 = p1.Next
		}
		if l1!=nil{
			l1 = l1.Next
		}
		if l2!=nil{
			l2 = l2.Next
		}
	}
	return p
}

func getVal(l *ListNode) int {
	if l != nil {
		return l.Val
	}
	return 0
}
